<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head th:include="/common/header" />

<link rel="stylesheet" href="/static/assets/webuploader/webuploader.css">
<style type="text/css">
.progressTip {
    padding-left: 30px;
}
</style>

<body>
    <!--用来存放文件信息-->
    <div id="uploader">
        <section class="content-header">
            <h1>视频上传<small>（如果需要重新上传视频，请刷新页面）</small></h1>
        </section>
        <section class="content">
            <div class="box box-widget">
                <div class="box-body">
                    <h3 id="selectFileName"></h3>
                    <div class="progress">
                        <div id="upload-progress-bar" class="progress-bar progress-bar-primary progress-bar-striped" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
                    </div>
                    <div class="btns">
                        <div id="picker">选择视频文件</div>
                        <button id="startBtn" class="btn btn-success">开始上传</button>
                        <button id="cancelBtn" class="btn btn-danger">取消上传</button>
                    </div>
                </div>
            </div>
            <div class="box box-solid" style="margin-top:20px">
                <div id="result" class="box-body">
                    <table id="dataGrid"></table>
                    <div id="toolbar">
                        <div class="btn-group">
                        </div>
                    </div>
                </div>
            </div>
            <input type="hidden" id="servletUrl" th:value="${servletUrl}" />
            <input type="hidden" id="accessKey" th:value="${accessKey}" />
        </section>
    </div>
    <!--引入JS-->
    <div th:include="/common/footer" />
    <script type="text/javascript" src="/static/assets/webuploader/webuploader.min.js"></script>

    <script type="text/javascript">
    var table;
    $(function() {
        initDataGrid();
    });

    function initDataGrid() {
        table = $.createTable("#dataGrid", {
            idField: "id",
            columns: [
                [{
                        title: "文件名称",
                        field: "name",
                        align: "left",
                        formatter: function(value, row, index) {
                            return "/" + value.replace(/\\/g,"/").substring(1);
                        }
                    },
                    {
                        title: "文件创建时间",
                        field: "lastUpdateTime",
                        formatter: "date"
                    },
                    {
                        title: "文件大小",
                        field: "size",
                        formatter: function(value, row, index) {
                            return value ? (value / 1024 / 1024).toFixed(2) + "M" : "-";
                        }
                    },
                    {
                        title: "操作",
                        align: "center",
                        width: "100px",
                        events: {
                            'click .remove': function(e, value, row, index) {
                                remove(row);
                            }
                        },
                        formatter: function operateFormatter(value, row, index) {
                            var html = '<button class="remove btn btn-xs btn-danger"><i class="glyphicon glyphicon-remove"></i>删除</button>';
                            return html;
                        }
                    }
                ]
            ],
            url: '/common/upload/find/file',
            searchbar: '#searchbar',
            showColumns: true,
            pagination: false,
            toolbar: "#toolbar",
            showRefresh: true
        });
    }

    function remove(row) {
        if (row) {
            layer.confirm('确定删除文件吗?', function() {
                $.getAjax(encodeURI('/common/upload/delete/file?pelativePath=' + row.pelativePath), function() {
                    $.successMessage("删除成功");
                    table.refresh();
                });
            });
        }
    }

    var chunkSize = 5 * 1024 * 1024;
    var curTitle, curPercentage, $progressBar, $progress;

    // HOOK 这个必须要再uploader实例化前面
    WebUploader.Uploader.register({
        'before-send-file': 'beforeSendFile',
        'before-send': 'beforeSend'
    }, {
        beforeSendFile: function(file, a) {
            // Deferred对象在钩子回掉函数中经常要用到，用来处理需要等待的异步操作。
            var task = new $.Deferred();
            // 根据文件内容来查询MD5
            uploader.md5File(file).progress(function(percentage) { // 及时显示进度
                getProgressBar(file, percentage, "MD5");
            }).then(function(val) { // 完成
                file.md5 = val;
                // 进行md5判断
                $.post("/common/upload/check", { md5: file.md5, chunks: Math.ceil(file.size / chunkSize), name: file.name },
                    function(data) {
                        var status = data.status;
                        task.resolve();
                        if (status == 2) {
                            // 异常
                            layer.msg("上传文件异常", { icon: 5 });
                            uploader.skipFile(file);
                            file.pass = false;
                        } else if (status == 9) {
                            // 忽略上传过程，直接标识上传成功；
                            uploader.skipFile(file);
                            file.pass = true;
                        } else if (status == 1) {
                            // 部分已经上传到服务器了，但是差几个模块。
                            file.completedChunks = data.result;
                        }
                    });
            });

            return $.when(task);
        },
        beforeSend: function(block) {
            var task = new $.Deferred(),
                file = block.file,
                completedChunks = file.completedChunks,
                blockChunk = block.chunk,
                flag = true;

            if (completedChunks) {
                for (var i = 0; i < completedChunks.length; i++) {
                    if (blockChunk == completedChunks[i]) {
                        flag = false;
                        break;
                    }
                }
            }

            if (flag) {
                task.resolve();
            } else {
                task.reject();
            }
            return $.when(task);
        }
    });

    // 实例化
    var uploader = WebUploader.create({
        pick: {
            id: '#picker',
            label: '选择视频文件'
        },
        //dnd: '#dndArea',
        //paste: '#uploader',
        swf: '/static/assets/webuploader/Uploader.swf',
        chunked: true,
        chunkSize: chunkSize, // 字节 1M分块
        threads: 3,
        server: '/common/upload/chunk',
        auto: false,
        duplicate: true,
        // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
        disableGlobalDnd: true,
        fileNumLimit: 1,
        fileSizeLimit: 10 * 1024 * 1024 * 1024,
        fileSingleSizeLimit: 10 * 1024 * 1024 * 1024,
        // accept: {
        //     title: 'Video',
        //     extensions: 'avi,mov,rmvb,rm,flv,mp4,3gp',
        //     mimeTypes: 'video/*'
        // }
    });

    // 当有文件被添加进队列的时候
    uploader.on('fileQueued', function(file) {
        $("#selectFileName").html(file.name + '<small class="progressTip" id="progress-status"></small>');
        $progressBar = $('#upload-progress-bar');
        $progress = $('#progress-status');
        $progressBar.css('width', "0%");
    });

    //当某个文件的分块在发送前触发，主要用来询问是否要添加附带参数，大文件在开起分片上传的前提下此事件可能会触发多次。
    uploader.onUploadBeforeSend = function(obj, data) {
        var file = obj.file;
        data.md5 = file.md5;
        data.chunkSize = chunkSize;
    };

    // 上传中
    uploader.on('uploadProgress', function(file, percentage) {
        getProgressBar(file, percentage, "UPLOAD");
    });

    // 上传返回结果
    uploader.on('uploadSuccess', function(file) {
        //getProgressBar(file, percentage, "UPLOAD-SUCCESS");
    });

    uploader.on('uploadError', errorHandle);
    uploader.on('uploadComplete', completedHandle);


    uploader.on('uploadAccept', function(file, response) {
        if (response.status && response.status == 1) {
            var result = response.result;
            if (result == 1) {
                return true;
            }

            if (result == 9) {
                uploader.stop(true);
                completedHandle(file);
                return true;
            }

            if (result == 8) {
                uploader.stop(true);
                errorHandle(file);
                return true;
            }
        }
        return false;
    });

    // 文件上传
    $("#startBtn").on('click', function() {
        uploader.upload();
    });

    $("#cancelBtn").click(function() {
        uploader.stop(true);
        uploader.reset();
        clear();
    });

    function clear() {
        $("#selectFileName").html('');
        $progressBar = $('#upload-progress-bar');
        $progress = $('#progress-status');
        $progressBar.css('width', "0%");
    }

    function completedHandle(file) {
        getProgressBar(file, 100, "UPLOAD-SUCCESS");
        uploader.reset();
        table.refresh();
    }

    function errorHandle(file) {
        getProgressBar(file, 100, "UPLOAD-FAIL");
        uploader.reset();
    }

    function getProgressBar(file, percentage, type) {
        var progressPercentage,
            title,
            titleClass;

        if (type == 'MD5') {
            progressPercentage = parseInt(percentage * 20);
            title = "计算MD5";
            titleClass = ""
        } else if (type == 'UPLOAD-SUCCESS') {
            progressPercentage = 100;
            title = "上传成功";
        } else if (type == 'UPLOAD') {
            progressPercentage = parseInt(percentage * 80) + 20;
            title = "上传文件";
        } else if (type == 'UPLOAD-FAIL') {
            progressPercentage = percentage || curPercentage;
            title = "上传失败";
        }

        if (curTitle !== title || curPercentage !== progressPercentage) {
            curTitle = title;
            $progress.html(title + ':' + progressPercentage + "%");
        }

        if (curPercentage !== progressPercentage) {
            curPercentage = progressPercentage;
            $progressBar.css('width', progressPercentage + "%");
        }
    }
    </script>
</body>

</html>